using System;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Web.Mvc;
using Uber.Service;
using log4net;

namespace Uber.WebUI.Controllers
{
    public class AwfListenerController : Controller
    {
        const string PrivateKey = "722414782befa556d2ec0065f1cc4b81";
        private readonly IBuyAwfService buyAwfService;
        private readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public AwfListenerController(IBuyAwfService buyAwfService)
        {
            this.buyAwfService = buyAwfService;
        }

        private static string GetMD5Hash(string input)
        {
            var x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = Encoding.UTF8.GetBytes(input);
            bs = x.ComputeHash(bs);
            var s = new StringBuilder();
            foreach (byte b in bs) { s.Append(b.ToString("x2").ToLower()); }
            return s.ToString();
        }

        public ActionResult Listen()
        {
            var transactionId = Request["OrderReference"];
            var amount = decimal.Parse(Request["OrderSubTotalUSD"], NumberStyles.AllowDecimalPoint, new CultureInfo("en-US"));
            var quantity = Convert.ToInt32(Request["q"]);
            var custom = Request["referrer"];
             
            var hash = GetMD5Hash(Request["security_data"] + PrivateKey);

            if (!Request["security_data"].Contains(transactionId) || hash != Request["security_hash"])
                log.Warn(string.Format("invalid request| tid: {0} ; req amount: {1}; q: {2}; custom: {3} ", Request["txn_id"], Request["mc_gross"], Request["quantity"], Request["custom"]));
            else
                buyAwfService.PurchaseAwf(transactionId, custom, quantity, amount);

            return Content("OK");
        }
    }

    //public class AwfListenerPayPalController : Controller
    //{
    //    const string StrSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";
    //    const string StrLive = "https://www.paypal.com/cgi-bin/webscr";
    //    private readonly IBuyAwfService buyAwfService;
    //    private readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    //    public AwfListenerPayPalController(IBuyAwfService buyAwfService)
    //    {
    //        this.buyAwfService = buyAwfService;
    //    }

    //    public ActionResult Listen()
    //    {
    //        var formVals = new Dictionary<string, string> { { "cmd", "_notify-validate" } };

    //        var response = GetPayPalResponse(formVals, true);
    //        var transactionId = Request["txn_id"];
    //        var amount = decimal.Parse(Request["mc_gross"], NumberStyles.AllowDecimalPoint, new CultureInfo("en-US"));
    //        var quantity = Convert.ToInt32(Request["quantity"]);
    //        var custom = Request["custom"];

    //        if (response == "VERIFIED")
    //        {
    //            buyAwfService.PurchaseAwf(transactionId, custom, quantity, amount);
    //        }
    //        else
    //            if (response == "INVALID")
    //            {
    //                log.Warn(string.Format("invalid request| tid: {0} ; req amount: {1}; q: {2}; nid: {3} ", Request["txn_id"], Request["mc_gross"], Request["quantity"], Request["custom"]));
    //            }
    //            else
    //            {
    //                log.Info(string.Format("request {0}| tid: {1} ; req amount: {2}; q: {3}; nid: {4} ", response, Request["txn_id"], Request["mc_gross"], Request["quantity"], Request["custom"]));
    //            }

    //        return Content("OK");
    //    }

    //    private string GetPayPalResponse(Dictionary<string, string> formVals, bool useSandbox)
    //    {
    //        var paypalUrl = useSandbox ? StrSandbox : StrLive;

    //        var req = (HttpWebRequest)WebRequest.Create(paypalUrl);
    //        req.Method = "POST";
    //        req.ContentType = "application/x-www-form-urlencoded";
    //        var param = Request.BinaryRead(Request.ContentLength);
    //        var strRequest = Encoding.ASCII.GetString(param);

    //        var sb = new StringBuilder();
    //        sb.Append(strRequest);

    //        foreach (var key in formVals.Keys)
    //        {
    //            sb.AppendFormat("&{0}={1}", key, formVals[key]);
    //        }
    //        strRequest += sb.ToString();
    //        req.ContentLength = strRequest.Length;

    //        string response;
    //        using (var streamOut = new StreamWriter(req.GetRequestStream(), Encoding.ASCII))
    //        {
    //            streamOut.Write(strRequest);
    //            streamOut.Close();
    //            using (var streamIn = new StreamReader(req.GetResponse().GetResponseStream()))
    //            {
    //                response = streamIn.ReadToEnd();
    //            }
    //        }
    //        return response;
    //    }
    //}
}